package com.example.aopweaver.transaction;

import com.example.aopweaver.dao.UserDao;
import com.example.aopweaver.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @Author ifredomvip@gmail.com
 * @Date 2022/8/2 11:12
 * @Version 1.0.0
 * @Description
 **/

public class TransactionConfig {


    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private UserDao userDao;

    /**
     * 自我管理事务
     */
    public void selfManageTransaction(){
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                try {
                    UserEntity user = new UserEntity();
                    user.setName("transaction");
                    user.setSex("1");
                    userDao.insetOneUser();

                    int i = 1 / 0;

                } catch (Exception e) {
                    System.out.println("异常" + e);
                    // 回滚
                    status.setRollbackOnly();
                }
            }
        });
    }
}
